/**
 * 警示列表alarmSign.js
 * 版本号： v1.0.0
 */
$(function () {
    //查询所属项目绑定
    bindCombo_project("prid_");

    //设置时间
    var curr_time = new Date();
    $("#startDate").datetimebox("setValue", getFirstDay(curr_time) + " 00:00:00");
    $("#endDate").datetimebox("setValue", getFirstDay(curr_time) + " 23:59:59");
    var startDate = $("#startDate").datetimebox("getValue");
    var endDate = $("#endDate").datetimebox("getValue");


    /**
     * 警示信息
     */
    var lastChecked = 0;
    //如果是点击未处理警报进入的，需要对url进行处理
    var alarmStatus = $("#alarmStatus").val();
    var alarmCategory = $("#alarmCategory").val();
    var url = CONTEXT_PATH + '/alarmSign/getAlarmList.do?';
    if (alarmStatus == 1) {
        url += "&alarmStatus=1";
    }
    if(alarmCategory){
        url += "&alarmCategory="+alarmCategory;
    }
    $("#alarmSign_dataList").datagrid({
        fit: true,
        fitColumns: true,
        method: "POST",
        rownumbers: true,
        singleSelect: true,
        queryParams:{startDate:startDate, endDate:endDate},
        pagination: true,
        border: false,
        pageSize: 10,
        pageNumber: 1,
        striped: true,
        pageList: [10, 30, 50, 100],
        url: url,
        idField: 'alId',
        frozenColumns: [[
            {field: 'alId', checkbox: true}
        ]],
        columns: [
            [
                {field: 'deviceName', title: '设备名称', width: 160, align: 'left', fixed: true},
                {field: 'deviceId', title: '设备编号', width: 120, fixed: true},
                {
                    field: 'project', title: '所属项目', width: 180, fixed: true,
                    formatter: function (value) {
                        if (value) {
                            return value.prName
                        }
                    }
                },
                {
                    field: 'unitOperator', title: '施工单位名称', width: 120, fixed: true,
                    formatter: function (value) {
                        if (value) {
                            return value.unitName
                        }
                    }
                },
                {field: 'alarmContent', title: '警报内容', width: 160, fixed: true},
                {
                    field: 'alarmType', title: '警报类型', width: 60, fixed: true, align: "center",
                    formatter: function (val) {
                        if (val == 1) return "<span style='color: green; font-weight: bold'>警报</span>";
                        if (val == 2) return "<span style='color: red; font-weight: bold'>预警</span>";
                    }
                },
                {
                    field: 'alarmStatus', title: '警示状态', width: 60, fixed: true, align: "center",
                    formatter: function (val) {
                        if (val == 1) return "<span style='color: red; font-weight: bold'>未处理</span>";
                        if (val == 2) return "<span style='color: green; font-weight: bold'>已处理</span>";
                    }
                },
                {field: 'alarmTime', title: '报警时间', width: 140}
            ]
        ],
        onCheck: function (rowIndex, rowData) {
            var row = $("#alarmSign_dataList").datagrid("getChecked");
            if (row && rowIndex == lastChecked) {
                $('#alarmSign_dataList').datagrid("unselectAll");//取消选中当前所有行
                lastChecked = null;
            } else {
                lastChecked = rowIndex;
            }
        },
        onLoadSuccess: function (data) {
            if (data.rows.length > 0) {
                lastChecked = null;
                $("#alarmSign_dataList").datagrid("selectRow", 0);
            }
        }
    });

    //定义可操作按钮
    $("#alarmSign_menu").dialog({
        title: '',
        width: 'auto',
        height: 35,
        closed: false,
        cache: false,
        inline: true,
        modal: false,
        border: false,
        toolbar: createToolbar()
    });
});


/**
 * 创建toolbar按钮组
 * @returns {Array}
 */
var viewIcon = "";
function createToolbar() {
    var toolbar = [];
    var falg = false;
    for (var j = 0; j < btnOptions.length; j++) {
        if (false != btnOptions[j].value) {
            falg = true;
            break;
        }
    }
    if (!falg) {
        //不存在按钮
        toolbar.push({});
    } else {
        //存在按钮
        for (var i = 0; i < btnOptions.length; i++) {
            if (false != btnOptions[i].value) {
                //查询按钮
                if ("searchBtn" == btnOptions[i].key) {
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            alarmSign_doSearch();
                        }
                    });
                }
                //详情按钮
                if ("viewBtn" == btnOptions[i].key) {
                    viewIcon = btnOptions[i].value.iconCls;
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            alarmSign_view(viewIcon);
                        }
                    });
                }
                //导出按钮
                if ("exportBtn" == btnOptions[i].key) {
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            alarmSign_export();
                        }
                    });
                }
                //处理按钮
                if ("resolveBtn" == btnOptions[i].key) {
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            alarmSign_resolve();
                        }
                    });
                }
            }
        }
        return toolbar;
    }
}

/**
 * 查看员工
 */
function alarmSign_view(iconCls) {
    var row = $("#alarmSign_dataList").datagrid("getSelected");
    if (row == null) {
        $.messager.show({title: '操作提示', msg: "请选择需要查看的警示详情", timeout: 3000, showType: "slide"});
        return;
    }
    //IFRAM打开窗口
    layoutSub(jsxq.id, jsxq.url + row.alId, iconCls, jsxq.closable, jsxq.title);
}

/**
 * 所属项目bind事件
 * @param projectControl
 */
function bindCombo_project(projectControl) {
    $.ajax({
        url: CONTEXT_PATH + "/project/getProjectListForCombo.do",
        type: "get",
        success: function (data) {
            var obj = JSON.parse(data);
            var projectCombo = [{'text': '--请选择--', 'value': ''}];
            for (var i = 0; i < obj.length; i++) {
                projectCombo.push({"text": obj[i].prName, "value": obj[i].prId});
            }
            $("#" + projectControl).combobox("loadData", projectCombo);
        }
    })
}

/**
 * 执行查询
 */
function alarmSign_doSearch() {
    //刷新页码
    refreshPageNumber("alarmSign_dataList");
    //查询数据
    var url = CONTEXT_PATH + '/alarmSign/getAlarmList.do?';
    $("#alarmSign_dataList").datagrid("options").url = url;
    $("#alarmSign_dataList").datagrid("reload", {
        prId: $("#prid_").combobox("getValue"),
        alarmType: $("#alarmType_").combobox("getValue"),
        alarmStatus: $("#alarmStatus_").combobox("getValue"),
        alarmCategory: $("#alarmCategory_").combobox("getValue"),
        startDate: $("#startDate").datetimebox("getValue"),
        endDate: $("#endDate").datetimebox("getValue")
    });
    $("#alarmSign_dataList").datagrid("clearSelections");
}

/***
 * 动态刷新页面
 * @param dgId
 */
function refreshPageNumber(dgId) {
    //获取dataGrid的列表对象属性
    var $datagrid = $("#" + dgId).datagrid("options");
    if ($datagrid != undefined) {
        $datagrid.pageNumber = 1;
    }
    //获取dataGrid的分页对象
    var $getPager = $("#" + dgId).datagrid('getPager');
    var $pagination = $($getPager).pagination("options");
    if ($pagination != undefined) {
        $pagination.pageNumber = 1;
    }
}

/**
 * 导出起重机械警示数据
 */
function alarmSign_export() {
    //判断没有选中数据时，无法导出
    var row = $("#alarmSign_dataList").datagrid("getSelected");
    if (row == null) {
        $.messager.show({title: '操作提示', msg: "没有数据无法导出", timeout: 3000, showType: "slide"});
        return;
    }
    //构建数据表的二维数组的DATA
    var sheetData = [];
    //每一行的数据
    var rowData = [];
    //从页面上的表格数据中获取到数据表格的所有数据，是一个二维数据结构
    var rows = $('#alarmSign_dataList').datagrid("getRows");
    //获取数据表中未冻结的所有列
    var columns = $('#alarmSign_dataList').datagrid("options").columns[0];
    //设置列表头行（描述行）
    //加载未被冻结的列名
    for (var i = 0; i < columns.length; i++) {
        rowData.push(columns[i].title);
    }
    //将构建好的第一行描述列的数据放入二维数据表的二维数组中。
    sheetData.push(rowData);

    var specialFields = ["project", "unitOperator", "alarmType"];
    //遍历真实数据行
    for (var i = 0; i < rows.length; i++) {
        //将行数据置为空
        rowData = [];
        for (var j = 0; j < columns.length; j++) {
            if ($.inArray(columns[j].field, specialFields) != -1) {
                if (columns[j].field == "project") {
                    if (rows[i][columns[j].field] && rows[i][columns[j].field].prName != null) {
                        rowData.push(rows[i][columns[j].field].prName.toString());
                    } else {
                        rowData.push("");
                    }
                }
                if (columns[j].field == "unitOperator") {
                    if (rows[i][columns[j].field] && rows[i][columns[j].field].unitName != null) {
                        rowData.push(rows[i][columns[j].field].unitName.toString());
                    } else {
                        rowData.push("");
                    }
                }
                if (columns[j].field == "alarmType") {
                    if (rows[i].deviceId != null) {
                        rowData.push(rows[i][columns[j].field] - 1 === 0 ? "警报" : "预警");
                    } else {
                        rowData.push("");
                    }
                }
            } else {
                if (rows[i][columns[j].field] != null) {
                    rowData.push(rows[i][columns[j].field].toString());
                } else {
                    rowData.push("");
                }
            }
        }
        //一行数据加载完后往数据表格二维数组中push
        sheetData.push(rowData);
    }
    /* build worksheet from the grid data */
    var ws = XLSX.utils.aoa_to_sheet(sheetData);

    /* build up workbook */
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '导出数据');

    /* generate download */
    XLSX.writeFile(wb, "警示信息" + new Date().format("yyyy-MM-dd hh-mm-ss") + ".xlsx");

}

/**
 * 处理警报
 */
function alarmSign_resolve() {
    var row = $("#alarmSign_dataList").datagrid("getSelected");
    var checked = $("#alarmSign_dataList").datagrid("getChecked");
    if (!checked || checked.length == 0) {
        $.messager.show({title: '操作提示', msg: "请选择要处理的警报", timeout: 3000, showType: "slide"});
        return;
    }
    if (row.alarmStatus == 2) {
        $.messager.show({title: '操作提示', msg: "请选择未处理状态的警报", timeout: 3000, showType: "slide"});
        return;
    }
    window.location.href = CONTEXT_PATH + "/alarmSign/resolve.do?alId=" + row.alId;
}

/**
 * 点击警报为未处理，直接跳转到处理界面
 * @param index
 */
function alarmSign_handle(index) {
    $('#alarmSign_dataList').datagrid('selectRow',index);
    var row = $('#alarmSign_dataList').datagrid('getSelected');
    window.location.href = CONTEXT_PATH + "/alarmSign/resolve.do?alId=" + row.alId;
}

/**
 * 点击已处理跳转详情
 * @param index
 */
function alarmSign_detail(index){
    $('#alarmSign_dataList').datagrid('selectRow',index);
    var row = $('#alarmSign_dataList').datagrid('getSelected');
    //IFRAM打开窗口
    layoutSub(jsxq.id, jsxq.url + row.alId, viewIcon, jsxq.closable, jsxq.title);
}

